package com.fBlog.service.impl;


import java.util.*;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fBlog.dao.impl.CommentDaoI;
import com.fBlog.dao.impl.SpeakDaoI;
import com.fBlog.pojo.Comment;
import com.fBlog.pojo.Speak;
import com.fBlog.pojo.Tcomment;
import com.fBlog.pojo.Tspeak;


@Service
public class SpeakServiceImpl implements SpeakServiceI{

	@Autowired
	private SpeakDaoI speakDao;
	@Autowired
	private CommentDaoI commentDao;

	//通过家庭id获取所有成员的动态信息
	@Override
	public List<Speak> getSpeaks(String familyId) {
		List<Speak> l = new ArrayList<Speak>();
		List<Tspeak> tl = speakDao.find("from Tspeak t where t.user.family.id = '"+familyId+"' order by t.createTime desc");
		for(Tspeak t : tl){
			Speak s = new Speak();
			BeanUtils.copyProperties(t, s);
			s.setUserId(t.getUser().getId());
			s.setUserName(t.getUser().getUserName());
			s.setUserCreateTime(t.getUser().getCreateTime());
			l.add(s);
		}
		return l;
	}

	@Override
	public Map<String, List<Comment>> getComments(List<Speak> l) {
		Map<String,List<Comment>> map= new HashMap<String,List<Comment>>();
		//遍历所有动态，获取id，并查找所有对应的评论
		for(Speak s : l){
			String speakId = s.getId();
			List<Comment> list = new ArrayList<Comment>();
			List<Tcomment> tc = commentDao.find("from Tcomment t where t.speak.id = '"+speakId+"' order by t.createTime");
			for(Tcomment t : tc){
				Comment c = new Comment();
				BeanUtils.copyProperties(t, c);
				//将动态id放入comment中
				c.setSpeakId(t.getSpeak().getId());
				if(t.getComment()!=null){
					c.setCommentId(t.getComment().getId());
				}
				list.add(c);
			}
			map.put(speakId, list);
		}
		return map;
	}

	@Override
	public String addDynamics(String uniqueName, String userId,String content) {
		String pct = "";
		String id = UUID.randomUUID().toString();
		String url = "images\\\\speakPicture\\\\";
		//判断该相片是否存在在相应的相册文件夹中
		if(!uniqueName.equals("")){
			pct = url+uniqueName;
		}
		String sql = "insert into tspeak (id,picture,content,createTime,viewQty,good,USERID) values ('"+id+"','"+pct+"','"+content+"',now(),0,'','"+userId+"')";
		speakDao.executeSql(sql);
		return "0";
	}

	@Override
	public void addComment(String userName, String speakId, String comment) {
		String id = UUID.randomUUID().toString();
		String sql = "insert into tcomment (id,content,userName,createTime,hasCom,SPEAKID) values ('"+id+"','"+comment+"','"+userName+"',now(),0,'"+speakId+"')";
		speakDao.executeSql(sql);
	}

	@Override
	public Map<String, List<Comment>> getSelfComments(String familyId) {
		Map<String,List<Comment>> map= new HashMap<String,List<Comment>>();
		//获取当前家庭的所有评论
		List<Tcomment> l = commentDao.find("from Tcomment t where t.speak.user.family.id ='"+familyId+"' order by t.createTime");
		for(Tcomment tc : l){
			if(tc.isHasCom()){
				String commentId = tc.getId();
				List<Comment> list = new ArrayList<Comment>();
				//通过评论id查出所有回复
				List<Tcomment> l1 = commentDao.find("from Tcomment t where t.comment.id = '"+commentId+"' order by t.createTime");
				for(Tcomment tcm : l1){
					Comment ct = new Comment();
					BeanUtils.copyProperties(tcm, ct);
					ct.setCommentId(tcm.getComment().getId());
					list.add(ct);
				}
				map.put(commentId, list);
			}
		}
		return map;
	}

	@Override
	public void addSelfComment(String userName, String commentId, String content) {
		String id = UUID.randomUUID().toString();
		String sql = "insert into tcomment (id,content,userName,createTime,hasCom,COMMENTID) values ('"+id+"','"+content+"','"+userName+"',now(),0,'"+commentId+"')";
		String sql1 = "update tcomment set hasCom = 1 where id = '"+commentId+"'";
		speakDao.executeSql(sql1);
		speakDao.executeSql(sql);
	}

	@Override
	public void addGood(String userName,String speakId) {
		String good = "";
		//查出这条说说
		Tspeak speak = speakDao.get("from Tspeak t where t.id = '"+speakId+"'");
		//获取这条说说目前所有点赞的用户（字符串逗号相连）
		if(speak.getGood()!=null){
			good = speak.getGood();
			if(good.equals("")){
				good += userName;
			}else{
				String go = "";
				//记录是否存在该用户名
				Boolean b = false;
				//判断字符串中有没有当前用户名，有的话就是取消点赞，没有就是点赞
				//将字符串已逗号分隔，取得所有点赞用户名
				String[] gs = good.split("，");
				//遍历点赞用户名，判断是否存在该用户名
				int j = 0;
				for(int i=0;i<gs.length;i++){
					if(gs[i].equals(userName)){
						b=true;
						j=i;
					}
				}
				if(b){
					  if(gs.length>1){
						//把最后一个元素替代指定的元素
						  gs[j] = gs[gs.length-1];
						  //数组缩容
						  gs = Arrays.copyOf(gs, gs.length-1);
						  for(String s : gs){
							  go+=s+"，";
						  }
						  go = go.substring(0, go.length()-1);
					  }
					  good = go;
				}else{
					good+="，"+userName;
				}
			}
		}else{
			good += userName;
		}
		
		//更新good字段
		String sql = "update tspeak set good = '"+good+"' where id = '"+speakId+"'";
		speakDao.executeSql(sql);
	}

	@Override
	public List<Speak> getThisUserSpeak(String familyId, String userId) {
		List<Speak> l = new ArrayList<Speak>();
		List<Tspeak> tl = speakDao.find("from Tspeak t where t.user.id = '"+userId+"' and t.user.family.id = '"+familyId+"' order by t.createTime desc");
		if(tl!=null && tl.size()>0){
			for(Tspeak ts : tl){
				Speak s = new Speak();
				BeanUtils.copyProperties(ts,s);
				s.setUserCreateTime(ts.getUser().getCreateTime());
				s.setUserId(ts.getUser().getId());
				s.setUserName(ts.getUser().getUserName());
				//统计该动态的点赞人数
				if(ts.getGood()!=null && !ts.getGood().trim().equals("")){
					int goodQty = 0;
					String []goods = ts.getGood().split("，");
					goodQty = goods.length;
					s.setGoodQty(goodQty);
				}else{
					s.setGoodQty(0);
				}
				//统计该动态的评论数量
				int comQty = 0;
				long tcomQty = 0;
				tcomQty = commentDao.count("select count(*) from Tcomment t where t.speak.id = '"+ts.getId()+"'");
				if(comQty>=0){
					comQty = (int)tcomQty;
				}
				s.setComQty(comQty);
				//统计该动态的浏览次数，以当前浏览次数加上当前时间的描述来模拟
				//获取当前时间的秒数
				int second = Calendar.getInstance().get(Calendar.SECOND);
				int nowVq = ts.getViewQty()+second/30;
				s.setViewQty(nowVq);
				speakDao.executeSql("update tspeak set viewQty = '"+nowVq+"' where id = '"+ts.getId()+"'");
				l.add(s);
			}
		}
		return l;
	}

	@Override
	public boolean deleteCom(String commentId) {
		boolean b = false;
		//如果该评论下有回复，先删回复
		List<Tcomment> l = commentDao.find("from Tcomment t where t.comment.id = '"+commentId+"'");
		if(l!=null && l.size()>0){
			for(Tcomment t : l){
				commentDao.executeSql("delete from tcomment where id = '"+t.getId()+"'");
			}
		}
		commentDao.executeSql("delete from tcomment where id = '"+commentId+"'");
		b=true;

		return b;
	}

	@Override
	public boolean deleteSpeak(String speakId) {
		boolean b = false;
		//首先根据动态id查询动态下的所有评论
		List<Tcomment> l = commentDao.find("from Tcomment t where t.speak.id ='"+speakId+"'");
		if(l!=null && l.size()>0){
			for(Tcomment t : l){
				//查询每条评论下的所有回复
				List<Tcomment> lc = commentDao.find("from Tcomment t where t.comment.id ='"+t.getId()+"'");
				if(lc!=null && lc.size()>0){
					for(Tcomment tc : lc){
						commentDao.executeSql("delete from tcomment where id = '"+tc.getId()+"'");
					}
				}
				commentDao.executeSql("delete from tcomment where id = '"+t.getId()+"'");
			}
		}
		speakDao.executeSql("delete from tspeak where id = '"+speakId+"'");
		b=true;

		return b;
	}
}
